﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Phone.Tasks;

namespace Qplus.UI
{
    public partial class ChatFriend : PhoneApplicationPage
    {
        RecordControl recRC, senRC;
        ScrollViewer smileySv = new ScrollViewer() { Height = 300, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto};
        public ChatFriend()
        {
            InitializeComponent();
            smileyInit();
            _loop.Duration = TimeSpan.FromMilliseconds(500d);
            _loop.Completed += new EventHandler(_loop_Completed);
            speakBtn.AddHandler(ButtonEx.MouseLeftButtonDownEvent, new MouseButtonEventHandler(speakBtn_MouseLeftButtonDown), true);
            speakBtn.AddHandler(ButtonEx.MouseLeftButtonUpEvent, new MouseButtonEventHandler(speakBtn_MouseLeftButtonUp), true);
        }
//on loaded
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("nickName"))
            {
                this.friendName.Text = NavigationContext.QueryString["nickName"];
            }
        }
//friendInfo
        private void friendInfoBtnEx_Click(object sender, RoutedEventArgs e)
        {
            PopupContainer pc = new PopupContainer(this);
            PopupUserInfo popupUserInfo = new PopupUserInfo() { IsFriend = true };
            //popupUserInfo.starChatBtnEx.Click += starChatBtnEx_Click;
            //popupUserInfo.starChatBtnEx.Visibility = System.Windows.Visibility.Visible;
            pc.Show(popupUserInfo);
        }
//Records
        private void chatRecordsListBox_Update()
        {
        }
//img select
        private void selectBtn_Click(object sender, RoutedEventArgs e)
        {
            if (popupGrid.Visibility == System.Windows.Visibility.Collapsed)
            {
                popupGrid.Visibility = System.Windows.Visibility.Visible;
            }
            else if (popupGrid.Visibility == System.Windows.Visibility.Visible)
            {
                popupGrid.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void smileyInit()
        {
            WrapPanel smileyWP = new WrapPanel() { MaxWidth = 480 };
            for (int i = 0; i < 99; i++)
            {
                SmileyControl smCtrl = new SmileyControl() { Editable = false, Index = i + 1, Margin = new Thickness(2) };
                smileyWP.Children.Add(smCtrl);
            }
            smileySv.Content = smileyWP;
        }
        private void smileyBtnEx_Click(object sender, RoutedEventArgs e)
        {
            popupGrid.Visibility = System.Windows.Visibility.Collapsed;
            PopupContainer pc = new PopupContainer(this);
            pc.Show(smileySv);
        }
        private void picBtnEx_Click(object sender, RoutedEventArgs e)
        {
            popupGrid.Visibility = System.Windows.Visibility.Collapsed;
            PhotoChooserTask picCTask = new PhotoChooserTask();
            picCTask.Show();
            picCTask.Completed += new EventHandler<PhotoResult>(picCTask_Completed);
        }
        void picCTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bmpSource = new BitmapImage();
                bmpSource.SetSource(e.ChosenPhoto);
                //添加到聊天记录中
                TextBlock timeTB = new TextBlock()
                {
                    Text = DateTime.Now.ToString(),
                    Foreground = new SolidColorBrush(Colors.Gray),
                    TextAlignment = TextAlignment.Center,
                    Width = 480,
                };
                recRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.receivePic,
                    Pic = bmpSource,
                };
                senRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.sendPic,
                    Pic = bmpSource,
                };
                recordWP.Children.Add(timeTB);
                recordWP.Children.Add(recRC);
                recordWP.Children.Add(senRC);
            }
            else
            {
                //do nothing
            }
        }
        private void cameraBtnEx_Click(object sender, RoutedEventArgs e)
        {
            popupGrid.Visibility = System.Windows.Visibility.Collapsed;
            CameraCaptureTask camCTask = new CameraCaptureTask();
            camCTask.Show();
            camCTask.Completed += new EventHandler<PhotoResult>(camCTask_Completed);
        }
        void camCTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bmpSource = new BitmapImage();
                bmpSource.SetSource(e.ChosenPhoto);
                //添加到聊天记录中
                TextBlock timeTB = new TextBlock()
                {
                    Text = DateTime.Now.ToString(),
                    Foreground = new SolidColorBrush(Colors.Gray),
                    TextAlignment = TextAlignment.Center,
                    Width = 480,
                };
                recRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.receivePic,
                    Pic = bmpSource,
                };
                senRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.sendPic,
                    Pic = bmpSource,
                };
                recordWP.Children.Add(timeTB);
                recordWP.Children.Add(recRC);
                recordWP.Children.Add(senRC);
            }
            else
            {
                //do nothing
            }
        }
//switch msg voice
        private void msgModeBtn_Click(object sender, RoutedEventArgs e)
        {
            msgModeBtn.Visibility = System.Windows.Visibility.Collapsed;
            speakBtn.Visibility = System.Windows.Visibility.Collapsed;
            inputSV.Visibility = System.Windows.Visibility.Visible;
            //inputRTC.Visibility = System.Windows.Visibility.Visible;
            sendMsgBtn.Visibility = System.Windows.Visibility.Visible;
            voiceModeBtn.Visibility = System.Windows.Visibility.Visible;
        }
        private void voiceModeBtn_Click(object sender, RoutedEventArgs e)
        {
            voiceModeBtn.Visibility = System.Windows.Visibility.Collapsed;
            inputSV.Visibility = System.Windows.Visibility.Collapsed;
            //inputRTC.Visibility = System.Windows.Visibility.Collapsed;
            sendMsgBtn.Visibility = System.Windows.Visibility.Collapsed;
            msgModeBtn.Visibility = System.Windows.Visibility.Visible;
            speakBtn.Visibility = System.Windows.Visibility.Visible;
        }
//msg
        private void sendMsgBtn_Click(object sender, RoutedEventArgs e)
        {
            var var = inputRTC.richTxtCtrlWP.Children.ElementAt(0);
            if (inputRTC.richTxtCtrlWP.Children.Count > 0 || (var as TextBox).Text != "")
            {
                //RecordControl newRecMsg = new RecordControl() { MsgType = msgTypeEnum.receiveTxt };
                //RecordControl newSenMsg = new RecordControl() { MsgType = msgTypeEnum.sendTxt };
                //inputRTC.contentCopy(newRecMsg.recRTC);
                //inputRTC.contentCopy(newSenMsg.senRTC);
                //recordWP.Children.Add(newRecMsg);
                //recordWP.Children.Add(newSenMsg);

                //TextBox tmp2 = new TextBox() { Text = "顶替", Width = 100, Foreground = new SolidColorBrush(Colors.Black), Style = (Style)App.Current.Resources["noBorderTB"] };
                //this.inputRTC.richTxtCtrlWP.Children.Add(tmp2);
                //testWP = newRecMsg.recRTC.richTxtCtrlWP;
                //TextBlock tmptb = new TextBlock() { Text = "123", Foreground = new SolidColorBrush( Colors.Red)};
                //testWP.Children.Add(tmptb);
            }
//TextBox
            //bool isMsgCanSend = false;
            if (inputTBox.Text != "")
            {
                TextBlock timeTB = new TextBlock()
                {
                    Text = DateTime.Now.ToString(),
                    Foreground = new SolidColorBrush(Colors.Gray),
                    TextAlignment = TextAlignment.Center,
                    Width = 480,
                    //HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                };
                RecordControl recRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.receiveTxt,
                    Msg = inputTBox.Text,

                };
                RecordControl senRC = new RecordControl()
                {
                    MsgType = msgTypeEnum.sendTxt,
                    Msg = inputTBox.Text,

                };
                recordWP.Children.Add(timeTB);
                recordWP.Children.Add(recRC);
                recordWP.Children.Add(senRC);
                inputTBox.Text = "";
            }
        }
        
//voice
        private int talkNum = 0;
        DateTime starTime, endTime;
        private Storyboard _loop = new Storyboard();
        void _loop_Completed(object sender, EventArgs e)
        {
                if (talkNum % 2 == 0)
                {
                    talk_ring1.Visibility = System.Windows.Visibility.Visible;
                    talk_ring2.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    talk_ring1.Visibility = System.Windows.Visibility.Collapsed;
                    talk_ring2.Visibility = System.Windows.Visibility.Visible;
                }
                talkNum++;
                _loop.Begin();
        }
        private void speakBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //开始录音
            starTime = DateTime.Now;
            //开始播放录音动画
            talkringGrid.Visibility = System.Windows.Visibility.Visible;
            _loop.Begin();
        }
        private void speakBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //录音结束
            endTime = DateTime.Now;
            
            //停止播放录音动画
            talk_ring1.Visibility = System.Windows.Visibility.Collapsed;
            talk_ring2.Visibility = System.Windows.Visibility.Collapsed;
            talkringGrid.Visibility = System.Windows.Visibility.Collapsed;
            _loop.Stop();
            talkNum = 0;

            //添加到聊天记录中
            TextBlock timeTB = new TextBlock()
            {
                Text = DateTime.Now.ToString(),
                Foreground = new SolidColorBrush(Colors.Gray),
                TextAlignment = TextAlignment.Center,
                Width = 480,
                //HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
            };
            //Grid timeGrid = new Grid();
            //timeGrid.Children.Add(timeTB);
            recRC = new RecordControl()
            {
                MsgType = msgTypeEnum.receiveVoice,
                Msg = (endTime - starTime).Minutes.ToString() + '\'' + (endTime - starTime).Seconds.ToString() + '\"',
                VoiceLength = (int)(endTime - starTime).TotalSeconds * 15 + 80,
            };
            senRC = new RecordControl()
            {
                MsgType = msgTypeEnum.sendVoice,
                Msg = (endTime - starTime).Minutes.ToString() + '\'' + (endTime-starTime).Seconds.ToString() + '\"',
                VoiceLength = (int)(endTime - starTime).TotalSeconds * 15 + 80,
            };
            //senRC.sendVoice.Width = recRC.sendVoiceTxt.ActualWidth + 30;
            recordWP.Children.Add(timeTB);
            recordWP.Children.Add(recRC);
            recordWP.Children.Add(senRC);
            //recordSV.ScrollToVerticalOffset(recordWP.ActualHeight);
            if (recordSV.ViewportHeight + recordSV.VerticalOffset > recordSV.ExtentHeight - recordSV.ViewportHeight * 3)
            {
                //button1_Click(null, null);
            }
        }
//goto bottom
        private void recordWP_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            recordSV.ScrollToVerticalOffset(recordWP.ActualHeight);
        }

        #region TEST CODE
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            inputRTC.firstTxt.Text = inputRTC.ActualWidth.ToString();
            //inputRTC.firstTxt.Text = content.ActualHeight.ToString();
            //inputRTC.firstTxt.Text = inputRTC.ActualHeight.ToString();
            //recordSV.ScrollToVerticalOffset(recordSV.ExtentHeight);
            /*
            TextBlock testTB = new TextBlock()
            {
                Foreground = new SolidColorBrush(Colors.Black),
                Text = "receive:" + recRC.receiveGrid.ActualWidth.ToString() + ",send:" + senRC.sendGrid.ActualWidth.ToString()
            };
            recordWP.Children.Add(testTB);
             * */
        }

        private void NOTUSE_addSmiley(Grid smileyGrid)
        {
            for (int i = 0; i < 9; i++)
            {
                ColumnDefinition colDef = new ColumnDefinition();
                smileyGrid.ColumnDefinitions.Add(colDef);
            }
            for (int i = 0; i < 10; i++)
            {
                RowDefinition rowDef = new RowDefinition();
                smileyGrid.RowDefinitions.Add(rowDef);
            }
            for (int i = 0; i < 99; i++)
            {
                SmileyControl smCtrl = new SmileyControl() { Index = i + 1 };
                Grid.SetRow(smCtrl, i / 9);
                Grid.SetColumn(smCtrl, i % 9);
                smileyGrid.Children.Add(smCtrl);
                /*
                Border smileyBg = new Border() { Background = head.Background, Visibility = System.Windows.Visibility.Collapsed};
                Image smileyImg = new Image()
                {
                    Source = new BitmapImage(new Uri("/Qplus;component/Pic/smiley_" + (i + 1).ToString() + ".png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None
                };
                ButtonEx smileyPicBtnEx = new ButtonEx()
                {
                    Background = new SolidColorBrush(Colors.Red),
                    PressedBackground = new SolidColorBrush(Colors.Blue),
                };
                smileyBtnEx.Click += smileyPicBtnEx_Click;
                Grid.SetRow(smileyBg, i / 9);
                Grid.SetColumn(smileyBg, i % 9);
                Grid.SetRow(smileyImg, i / 9);
                Grid.SetColumn(smileyImg, i % 9);
                Grid.SetRow(smileyPicBtnEx, i / 9);
                Grid.SetColumn(smileyPicBtnEx, i % 9);
                smileyGrid.Children.Add(smileyBg);
                smileyGrid.Children.Add(smileyImg);
                smileyGrid.Children.Add(smileyPicBtnEx);*/
            }
        }

        private void inputTBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            sendMsgBtn.IsEnabled = true;
            TextBox inputTB = sender as TextBox;
            int curPosition = inputTB.SelectionStart;
            ScrollViewer sv = inputTBox.Parent as ScrollViewer;
            double svPsition = 0;
            if (inputTB.Text.Length > 0)
            {
                svPsition = (double)curPosition / (double)inputTB.Text.Length * inputTB.ActualWidth;
            }
            if (svPsition != 0)
            {
                sv.ScrollToHorizontalOffset(svPsition);
            }
            else
            {
                sv.ScrollToHorizontalOffset(0);
            }
        }
        #endregion
    }
}